package com.nebula.salary.portal.controller.manage;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.nebula.salary.common.constants.ReturnMessage;
import com.nebula.salary.common.exception.CustomException;
import com.nebula.salary.model.dto.RoleDto;
import com.nebula.salary.portal.service.IRoleNavigationService;
import org.springframework.web.bind.annotation.*;

import com.nebula.salary.common.result.ServerResponse;
import com.nebula.salary.model.dto.RoleQueryDto;
import com.nebula.salary.model.pojo.Navigation;
import com.nebula.salary.model.vo.RoleVo;
import com.nebula.salary.portal.service.INavigationService;
import com.nebula.salary.portal.service.IRoleService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * 权限设置
 *
 * @author codex
 * @since 2022-03-02
 */
@RestController
@RequestMapping("/manage/roleSetting")
@Api(tags = "权限设置")
public class RoleSettingController {
    
    @Resource
    private IRoleService roleService;
    
    @Resource
    private INavigationService navigationService;
    
    @ApiOperation(value = "修改角色菜单权限")
    @PutMapping("/")
    public ServerResponse<String> updateRoleNavigation(@RequestBody RoleDto roleDto) {
    
        if (roleDto == null) {
            throw new CustomException(ReturnMessage.ILLEGAL_REQUEST);
        }
        
        if (roleDto.getRoleId() == null) {
            throw new CustomException("修改角色'" + roleDto.getRoleName() + "'失败，角色编号不正确");
        }
    
        roleService.checkRoleDataScope(roleDto.getRoleId());
        
        return roleService.updateRoleNavigation(roleDto) > 0
                ? ServerResponse.createBySuccessMessage(ReturnMessage.UPDATE_SUCCESS)
                : ServerResponse.createByErrorMessage(ReturnMessage.UPDATE_ERROR);
    }
    
    @ApiOperation(value = "获取所有有权的角色列表")
    @GetMapping("/list/all")
    public ServerResponse<List<RoleVo>> getPerAllList(RoleQueryDto role) {
        // 有权的角色列表
        return ServerResponse.createBySuccess(roleService.getPerAllList(role));
    }
    
    @ApiOperation(value = "根据角色ID获取菜单列表")
    @GetMapping("/{roleId}")
    public ServerResponse<Map<String, Object>> roleMenuSelect(@ApiParam(value = "角色ID", required = true)
                                                              @PathVariable Integer roleId) {
        List<Navigation> navigations = navigationService.treeSelect();
        Map<String, Object> map = new HashMap<>(2);
        map.put("checkedKeys", navigationService.selectMenuListByRoleId(roleId));
        map.put("menus", navigationService.buildMenuTreeSelect(navigations));
        
        return ServerResponse.createBySuccess(map);
    }
    
}
